<template>
  <a-card :bordered="false">
    <!-- 查询区域 -->
    <div class="table-page-search-wrappe">
      <a-form layout="inline" @keyup.enter.native="searchQuery">
        <a-row :gutter="24">
          <a-col :xl="6" :lg="7" :md="8" :sm="24">
            <a-form-item label="资质种类">
              <j-dict-select-tag
                placeholder="请选择资质种类"
                v-model="queryParam.certificateType"
                dictCode="certificate_type"
                @input="getCertificateName"
              />
            </a-form-item>
          </a-col>
          <a-col :xl="6" :lg="7" :md="8" :sm="24">
            <a-form-item label="证书名称">
              <j-multi-select-re-tag v-model="queryParam.certificateName" :options="dataOptions" placeholder="请选择证书名称"/>
            </a-form-item>
          </a-col>
          <a-col :xl="6" :lg="7" :md="8" :sm="24">
            <a-form-item label="归属公司">
              <select-Company-input v-model="queryParam.id" />
            </a-form-item>
          </a-col>
          <a-col :xl="6" :lg="7" :md="8" :sm="24">
              <a-form-item label="过期状态">
                <j-dict-select-tag
                  placeholder="请选择过期状态"
                  v-model="queryParam.isExpired"
                  dictCode="is_expired"
                />
              </a-form-item>
            </a-col>
            <a-col :xl="6" :lg="7" :md="8" :sm="24">
              <a-form-item label="包含关键字">
                <a-input v-model="queryParam.containsKey" placeholder="请输入关键字：至少包含两个字"/>
              </a-form-item>
            </a-col>
          <!-- <template v-if="toggleSearchStatus"></template> -->
          <a-col :xl="6" :lg="7" :md="8" :sm="24">
            <span style="float: left; overflow: hidden" class="table-page-search-submitButtons">
              <a-button type="primary" @click="searchQuery" icon="search">查询</a-button>
              <a-button type="primary" @click="searchReset" icon="reload" style="margin-left: 8px">重置</a-button>
              <!-- <a @click="handleToggleSearch" style="margin-left: 8px">
                {{ toggleSearchStatus ? '收起' : '展开' }}
                <a-icon :type="toggleSearchStatus ? 'up' : 'down'" />
              </a> -->
            </span>
          </a-col>
        </a-row>
      </a-form>
    </div>
    <!-- 查询区域-END -->

    <!-- 操作按钮区域 -->
    <div class="table-operator">
      <a-button type="primary" icon="download" @click="handleExportXls('公司资质')">导出</a-button>
    </div>

    <!-- table区域-begin -->
    <div style="margin-top: 10px">
      <a-table
        ref="table"
        size="middle"
        bordered
        rowKey="certificateId"
        :scroll="{ x: '150%' }"
        :components="draggableComponent"
        :columns="columns"
        :dataSource="dataSource"
        :pagination="false"
        :loading="loading"
        class="j-table-force-nowrap"
        :rowSelection="{ selectedRowKeys: selectedRowKeys, onChange: onSelectChange }"
      >
        <span slot="action" slot-scope="text, record">
          <a :class="record.isAction?'':'newColor'" @click="handlePreview(record)">预览</a>
          <a-divider type="vertical"/>
          <a :class="record.isAction?'':'newColor'" @click="handleModal(record)">下载</a>
        </span>
        <template slot="certificateNames" slot-scope="text, record">
          <a @click="showCertificateName(record)">{{ text?filterMultiDictText(dictOptions['certificateName'], text + '') : '' }} </a>
        </template>
      </a-table>
      <div style="margin-top: 20px;text-align: right;">
        <a-pagination
          v-model="ipagination.current"
          :total="ipagination.total"
          :pageSize="ipagination.pageSize"
          :showQuickJumper="ipagination.showQuickJumper"
          :showSizeChanger="ipagination.showSizeChanger"
          :showTotal="ipagination.showTotal"
          :pageSizeOptions="ipagination.pageSizeOptions"
          @change="handleTableChange"
          @showSizeChange="handleTableChange"
        />
      </div>
    </div>
    <ErpFinancialAuditModal ref="financialAudit" />
    <ErpCertificationChildModal ref="childModal" />
    <ExpirationReminder :dataOptions="dataOptions" :dictoptions="dictOptions" v-if="hasPerm"/>
    <watermark ref="watermarks" @ok="downloadOK"/>
    <a-modal
      title="请选择预览或下载"
      :visible="prebtnVisible"
      :footer="null"
      @cancel="handleNewPreCancel"
      :width="240"
    >
      <div style="text-align: center;">
        <a-button shape="circle" icon="search" @click="handlePreviews(prebtnFile)"/>
        <a-divider type="vertical"/>
        <a-button shape="circle" icon="download" @click="handleModals(prebtnFile)"/>
      </div>
    </a-modal>
  </a-card>
</template>

<script>
import { mixinDevice } from '@/utils/mixin'
import { DisabledAuthFilterMixin } from '@/mixins/DisabledAuthFilterMixin'
import { getAction } from '@/api/manage'
import { filterObj } from '@/utils/util'
import { JeecgListMixin } from '@/mixins/JeecgListMixin'
import { filterMultiDictText, initDictOptions } from '@/components/dict/JDictSelectUtil'
import ErpFinancialAuditModal from './modules/ErpFinancialAuditModal.vue'
import ErpCertificationChildModal from '@/views/erp/files/company/modules/ErpCertificationChildModal.vue'
import ExpirationReminder from './modules/ExpirationReminder.vue'
import watermark from './modules/watermark.vue'
import SelectCompanyInput from '@/views/scy/components/SelectCompanyInput'
import JMultiSelectReTag from '@/components/dict/JMultiSelectReTag.vue'
import PreviewPdf from '@/utils/previewPdfPublic'
import { axios } from '@/utils/request'
import moment from 'moment'
import { mapGetters } from 'vuex'
import { queryPermissionsByUser } from '@/api/api'
export default {
  name: 'ErrpCompanyQualificationList',
  mixins: [mixinDevice, DisabledAuthFilterMixin, JeecgListMixin],
  components: {
    ErpFinancialAuditModal,
    ErpCertificationChildModal,
    ExpirationReminder,
    SelectCompanyInput,
    watermark,
    JMultiSelectReTag
  },
  data() {
    return {
      description: '公司资质管理页面',
      ipagination: {
        current: 1,
        pageSize: 10,
        pageSizeOptions: ['5', '10', '20', '30', '50', '100', '200'],
        showTotal: (total, range) => {
          return range[0] + '-' + range[1] + ' 共 ' + total + ' 条'
        },
        showQuickJumper: true,
        showSizeChanger: true,
        total: 0
      },
      // 列定义
      columns: [
        {
          title: '序号',
          dataIndex: 'rowIndex',
          width: 60,
          align: 'center',
          customRender: (value, record, index) => {
            return {
              children: parseInt(index) + 1,
              attrs: { rowSpan: record.span }
            };
          }
        },
        {
          title: '归属公司',
          align: 'center',
          dataIndex: 'fileName',
          ellipsis: true,
          width: 260,
          customRender: (value, record, index) => {
            return {
              children: this.$createElement(
                'a',
                {
                  on: {
                      click: () => {
                      this.addEnterpriseInfo(record)
                  }
                }
              },
              [
                  this.$createElement(
                    'span'
                  ),
                  value
              ]),
              attrs: { rowSpan: record.span }
            };
          }
        },
        {
          title: '经营范围',
          align: 'center',
          dataIndex: 'bussiness',
          ellipsis: true,
          width: 260,
          customRender: (value, record, index) => {
            return {
              children: <a-tooltip placement="bottomLeft"><template slot="title">{value}</template>{value}</a-tooltip>,
              attrs: { rowSpan: record.span }
            };
          }
        },
        {
          title: '注册资金',
          align: 'center',
          width: 200,
          dataIndex: 'registerCapital',
          ellipsis: true,
          customRender: (value, record, index) => {
            return {
              children: value,
              attrs: { rowSpan: record.span }
            };
          }
        },
        {
          title: '发证日期',
          align: 'center',
          width: 200,
          dataIndex: 'issueCertificateDate',
          ellipsis: true,
          customRender: (value, record, index) => {
            return {
              children: value,
              attrs: { rowSpan: record.span }
            };
          }
        },
        {
          title: '原件保管人',
          align: 'center',
          dataIndex: 'custodian',
          ellipsis: true,
          width: 200,
          customRender: (value, record, index) => {
            return {
              children: value,
              attrs: { rowSpan: record.span }
            };
          }
        },
        {
          title: '附件',
          align: 'center',
          dataIndex: 'attachments',
          ellipsis: true,
          width: 200,
          customRender: (value, record, index) => {
            return {
              children: this.$createElement(
                'a',
                {
                  on: {
                      click: () => {
                      this.handleNewPre(value)
                  }
                }
              },
              [
                  this.$createElement(
                    'span'
                  ),
                  value
              ]),
              attrs: { rowSpan: record.span }
            };
          }
        },
        {
          title: '证书种类',
          align: 'center',
          dataIndex: 'certificateTypes',
          ellipsis: true,
          width: 200,
          customRender: (value, record, index) => {
            let text = ''
            if (!value) {
              text = ''
            } else {
              text = filterMultiDictText(this.dictOptions['certificateType'], value + '')
            }
            return {
              children: text,
              attrs: { rowSpan: record.childspan }
            };
          }
        },
        {
          title: '证书名称',
          align: 'center',
          width: 200,
          dataIndex: 'certificateNames',
          scopedSlots: { customRender: 'certificateNames' },
          ellipsis: true
        },
        {
          title: '发证单位',
          align: 'center',
          width: 200,
          dataIndex: 'issueCertificateUnit',
          ellipsis: true
        },
        {
          title: '发证日期',
          align: 'center',
          width: 200,
          dataIndex: 'issueCertificateDates',
          ellipsis: true
        },
        {
          title: '有效期',
          align: 'center',
          dataIndex: 'validPeriod',
          ellipsis: true,
          width: 200,
          customRender: (text, r) => {
            if (r.isAlways == 1) {
              return ''
            } else {
              return text
            }
          }
        },
        {
          title: '原件保管人',
          align: 'center',
          dataIndex: 'custodians',
          width: 200,
          ellipsis: true
        },
        {
          title: '专利分类',
          align: 'center',
          dataIndex: 'patentType',
          width: 200,
          ellipsis: true,
          customRender: (value, row, index) => {
            if (!value) {
              return ''
            } else {
              return filterMultiDictText(this.dictOptions['patentType'], value + '')
            }
          }
        },
        {
          title: '操作',
          dataIndex: 'action',
          align: 'center',
          fixed: 'right',
          width: 150,
          scopedSlots: {
            filterDropdown: 'filterDropdown',
            filterIcon: 'filterIcon',
            customRender: 'action'
          }
        }
      ],
      url: {
        list: '/api/erp/files/company/erpCompanyFiles/newList',
        delete: '/api/erp/files/company/erpCompanyFiles/delete',
        deleteBatch: '/api/erp/files/company/erpCompanyFiles/deleteBatch',
        exportXlsUrl: '/api/erp/files/company/erpCompanyCertificate/exportCompanyCertificateXls',
        importExcelUrl: 'api/erp/files/company/erpCompanyFiles/importExcel',
        downloadCertificate: '/api/erp/files/company/erpCompanyFiles/downloadCertificate'
      },
      dictOptions: {},
      toggleSearchStatus: false,
      loading: false /* 排序参数 */,
      isorter: {
        column: 'createTime',
        order: 'desc'
      },
      queryParam: {
        isExpired: '0'
      },
      /* 数据源 */
      dataSource: [],
      prebtnVisible: false,
      prebtnFile: '',
      authData: [],
      hasPerm: false,
      dataOptions: []
    }
  },
  created() {
    this.initDictConfig()
    this.getAuthFilter('companyQualification:expired')
    this.loadCertificateName(1)
    // this.loadData()
  },
  computed: {
    importExcelUrl: function () {
      return `${window._CONFIG['domianURL']}/${this.url.importExcelUrl}`
    },
    draggableComponent: function() {
      return this.dragResizable(this.columns)
    }
  },
  methods: {
    moment,
    ...mapGetters(['userInfo']),
    filterMultiDictText,
    async getCertificateName(typeCode) {
      this.$set(this.queryParam, 'certificateName', undefined)
      let res = await getAction('/api/erp/basecertinfo/field/nameList', { typeCode })
      if (res.success) {
        this.dataOptions = res.result.map(val => {
          return {
            ...val,
            value: val.id,
            text: val.certName
          }
        }) || []
      }
    },
    async loadCertificateName(arg) {
      let res = await getAction('/api/erp/basecertinfo/field/nameList', { typeCode: '' })
      if (res.success) {
        if (arg === 1) {
          this.dataOptions = res.result.map(val => {
            return {
              ...val,
              value: val.id,
              text: val.certName
            }
          }) || []
        }
        this.$set(this.dictOptions, 'certificateName', res.result.map(val => {
          return {
            label: val.certName,
            value: val.id,
            text: val.certName
          }
        }))
      }
      this.loadData(1)
    },
    showCertificateName(record) {
      let data = {
        certificateType: record.certificateTypes,
        certificateName: record.certificateNames,
        issueCertificateDate: record.issueCertificateDates,
        custodian: record.custodians,
        patentType: record.patentType,
        issueCertificateUnit: record.issueCertificateUnit,
        isAlways: record.isAlways,
        validPeriod: record.validPeriod,
        attachments: record.attachment,
        certFieldList: record.certFieldList,
        id: record.certId
      }
      this.$refs.childModal.edit(data)
      this.$refs.childModal.title = '详情'
      this.$refs.childModal.disableSubmit = true
      this.$refs.childModal.waterPdisable = true
    },
    getAuthFilter(code) {
      queryPermissionsByUser().then(response => {
        let hasPerm = true
        const authData = response.result.auth;
        let permissions = authData.map((item) => item.action)
        if (!permissions.includes(code)) {
          hasPerm = false;
        }
        this.hasPerm = hasPerm
      })
    },
    handleNewPre(value) {
      this.prebtnVisible = true
      this.prebtnFile = value
    },
    handleNewPreCancel() {
      this.prebtnVisible = false
      this.prebtnFile = ''
    },
    handleModals(value) {
      this.$refs.watermarks.visible = true
      this.$refs.watermarks.wValue = value
    },
    handleModal(record) {
      if (!record.attachment) {
        this.$message.warning('暂无附件！')
        return
      }
      if (record.isAlways && record.isAlways == 0 && moment(record.validPeriod).diff(moment(), 'days') < 0) {
        this.$message.warning('文件已过期，不支持预览/下载')
        return
      }
      this.$refs.watermarks.visible = true
      this.$refs.watermarks.wValue = record.attachment
    },
    downloadOK() {
      getAction(this.url.downloadCertificate).then(result => {})
    },
    handlePreviews(value) {
      let fileType = value.substr(-3)
      let text = `${this.userInfo().orgCodeTxt}-${this.userInfo().realname}-${this.userInfo().workNo}`
      let url = window.sessionStorage.getItem('baseUrl') + '/api/erpmng/sys/common/static/' + value
      axios({
        url: url,
        params: {},
        method: 'get',
        responseType: 'blob'
      }).then(res => {
        if (fileType === 'pdf') {
          new PreviewPdf({
            blob: res,
            docTitle: fileType,
            isAddWatermark: true, // 是否需要添加水印
            watermark: { // watermark必填 里面可以不填
              type: 'canvas',
              text: text
            }
          })
        } else {
          this.$message.error('非pdf文件不可查看')
        }
      })
    },
    // 预览
    handlePreview(record) {
      if (!record.attachment) {
        this.$message.warning('暂无附件！')
        return
      }
      if (record.isAlways && record.isAlways == 0 && moment(record.validPeriod).diff(moment(), 'days') < 0) {
        this.$message.warning('文件已过期，不支持预览/下载')
        return
      }
      let fileType = record.attachment.substr(-3)
      let text = `${this.userInfo().orgCodeTxt}-${this.userInfo().realname}-${this.userInfo().workNo}`
      let url = window.sessionStorage.getItem('baseUrl') + '/api/erpmng/sys/common/static/' + record.attachment
      axios({
        url: url,
        params: {},
        method: 'get',
        responseType: 'blob'
      }).then(res => {
        if (fileType === 'pdf') {
          new PreviewPdf({
            blob: res,
            docTitle: fileType,
            isAddWatermark: true, // 是否需要添加水印
            watermark: { // watermark必填 里面可以不填
              type: 'canvas',
              text: text
            }
          })
        } else {
          this.$message.error('非pdf文件不可查看')
        }
      })
    },
    addEnterpriseInfo(record) {
      this.$refs.financialAudit.visible = true
      this.$refs.financialAudit.edit(record)
    },
    initDictConfig() {
      initDictOptions('certificate_type').then((res) => {
        if (res.success) {
          this.$set(this.dictOptions, 'certificateType', res.result)
        }
      })
      initDictOptions('patent_type').then((res) => {
        if (res.success) {
          this.$set(this.dictOptions, 'patentType', res.result)
        }
      })
    },
    insert(arr, item, index) {
      return arr.slice(0, index).concat(item, arr.slice(index));
    },
    loadData(arg) {
      if (!this.url.list) {
        this.$message.error('请设置url.list属性!')
        return
      }
      // 加载数据 若传入参数1则加载第一页的内容
      if (arg === 1) {
        this.ipagination.current = 1
      }
      var params = this.getQueryParams() // 查询条件
      params.pageUrl = this.$route.path
      this.loading = true
      getAction(this.url.list, params)
        .then((res) => {
          if (res.success) {
            // update-begin---author:zhangyafei    Date:20201118  for：适配不分页的数据列表------------
            let dValue = res.result.records || res.result
            let arr = []
            dValue.map(dValueItem => {
              if (dValueItem.certificateList) {
                const len = dValueItem.certificateList.length;
                let carr = dValueItem.certificateList.reduce((result, item) => {
                  const key = item.certificateType
                  if (!result[key]) {
                    result[key] = []
                  }
                  result[key].push(item)
                  return result
                }, {})
                let childrr = []
                Object.keys(carr).map(zevel => {
                  let childLen = carr[zevel].length
                  childrr.push(...carr[zevel].map((dItem, index) => {
                    return {
                      ...dItem,
                      childspan: index === 0 ? childLen : 0
                    }
                  }))
                })
                childrr.map((timeDataItem, index) => {
                    arr = [
                    ...arr,
                    {
                      ...dValueItem,
                      issueCertificateDates: timeDataItem.issueCertificateDate,
                      attachment: timeDataItem.attachments,
                      validPeriod: timeDataItem.validPeriod,
                      custodians: timeDataItem.custodian,
                      certificateTypes: timeDataItem.certificateType,
                      certificateNames: timeDataItem.certificateName,
                      issueCertificateUnit: timeDataItem.issueCertificateUnit,
                      issueCertificateDates: timeDataItem.issueCertificateDate,
                      custodians: timeDataItem.custodian,
                      certFieldList: timeDataItem.certFieldList,
                      certId: timeDataItem.id,
                      patentType: timeDataItem.patentType ? timeDataItem.patentType : '无',
                      isAlways: timeDataItem.isAlways,
                      isAction: timeDataItem.isAlways == 1 ? true : moment(timeDataItem.validPeriod).diff(moment(), 'days') >= 0,
                      span: index === 0 ? len : 0, // 各自的rowSpan计算出来放入对象
                      childspan: timeDataItem.childspan
                    }
                  ]
                  return arr
                })
                // dValueItem.certificateList.map((timeDataItem,index)=>{
                //   arr = [
                //     ...arr,
                //     {
                //       ...dValueItem,
                //       issueCertificateDates: timeDataItem.issueCertificateDate,
                //       attachment: timeDataItem.attachments,
                //       validPeriod: timeDataItem.validPeriod,
                //       custodians:timeDataItem.custodian,
                //       certificateTypes: timeDataItem.certificateType,
                //       certificateNames: timeDataItem.certificateName,
                //       issueCertificateUnit: timeDataItem.issueCertificateUnit,
                //       patentType: timeDataItem.patentType?timeDataItem.patentType:'无',
                //       isAlways: timeDataItem.isAlways,
                //       isAction: timeDataItem.isAlways==1?true:moment(timeDataItem.validPeriod).diff(moment(),'days')>=0,
                //       span:index === 0 ? len : 0,  // 各自的rowSpan计算出来放入对象
                //     }
                //   ]
                //   return arr
                // })
              } else {
                arr = [
                  ...arr,
                  {
                    ...dValueItem,
                    isAction: false
                  }
                ]
              }
            })
            // let zIndex = 0
            // this.dataSource = arr.map((item, index) => {
            //   item.key = index;
            //   if(item.span==0){
            //   } else {
            //     item.rowIndex = ++zIndex
            //   }
            //   return item;
            // })
            this.dataSource = arr
            if (res.result.total) {
              this.ipagination.total = res.result.total
            } else {
              this.ipagination.total = 0
            }
            // 判断是否当前页没有数据且不为第一页
            // if (this.dataSource.length == 0 && this.ipagination.current != 1) {
            //   this.ipagination.current = this.ipagination.current - 1
            //   this.loadData(this.ipagination.current - 1)
            // }
            // update-end---author:zhangyafei    Date:20201118  for：适配不分页的数据列表------------
          } else {
            this.dataSource = []
            this.ipagination.total = 0
            this.$message.warning(res.message)
          }
          if (res.code === 510) {
            this.$message.warning(res.message)
          }
          this.loading = false
        })
        .catch((err) => {
          this.$message.warning(err.message)
        })
    },
    getQueryParams() {
      var param = Object.assign({}, this.queryParam, this.isorter)
      param.pageNo = this.ipagination.current
      param.pageSize = this.ipagination.pageSize
      return filterObj(param)
    },
    searchQuery() {
      this.loadData(1)
    },
    searchReset() {
      this.queryParam = {
        isExpired: '0'
      }
      this.loadCertificateName(1)
      // this.loadData(1)
    },
    handleToggleSearch() {
      this.toggleSearchStatus = !this.toggleSearchStatus
    },
    handleTableChange(page, pageSize) {
      this.ipagination.current = page
      this.ipagination.pageSize = pageSize
      this.loadData()
    }

  }
}
</script>
<style scoped>
@import '~@assets/less/common.less';
.newColor{
  color: #c9c9c9;
}
</style>
